<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <script>
      function timeout(time) {
        return new Promise(function (resolve, reject) {
          setTimeout(resolve, time);
        });
      }
      class SuperTask {
        constructor(maxTask = 2) {
          this.runingTask = 0;
          this.maxTask = maxTask;
          this.taskStack = [];
        }
        add(fn) {
          return new Promise((resolve, reject) => {
            this.taskStack.push({
              fn,
              resolve,
            });
            this._run();
          });
        }
        _run() {
          while (this.runingTask < this.maxTask && this.taskStack.length) {
            let { fn, resolve } = this.taskStack.shift();
            this.runingTask++;
            Promise.resolve(fn())
              .then(resolve)
              .finally(() => {
                console.log(this.runingTask, "this.runingTask--");
                this.runingTask--;
                this._run();
              });
          }
        }
      }
      let superTask = new SuperTask();
      function addTask(time, name) {
        superTask
          .add(() => timeout(time))
          .then(() => {
            console.log(`任务${name}完成`);
          });
      }
      addTask(10000, 1);
      addTask(5000, 2);
      addTask(3000, 3);
      addTask(4000, 4);
      addTask(5000, 5);
    </script>
  </body>
</html>
